<template>
  <div class="view_page weizhi2">
    <el-card
      class="box-card"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <!--卡片头部-->
      <div slot="header" class="clearfix">
        <!--左侧-->
        <div class="left">
          <div class="back-page">
            <div class="add-back" @click="back">
              <i class="fa fa-arrow-left" aria-hidden="true"></i>
              <span v-if="this.addtype == 'add'">新增设备列表</span>
              <span v-else>修改设备列表</span>
            </div>
          </div>
        </div>
        <div class="right">
          <el-button type="primary" @click="save()">保存</el-button>
          <!-- <el-button type="primary" @click="update()" v-if="addtype == 'update'"
            >保存</el-button
          > -->
        </div>
      </div>
      <!--卡片内容-->
      <div class="card-centont">
        <el-form :model="liveData" label-width="130px">
          <div style="display: flex;">
            <div style="width:50%">
              <el-form-item label="设备名称" :required="true">
                <el-input
                  v-model="liveData.name"
                  placeholder="请输入设备名称"
                ></el-input>
              </el-form-item>
            </div>
            <div style="width:50%">
              <el-form-item label="设备类型" :required="true">
                <el-select
                  filterable
                  v-model="liveData.equipment_type"
                  @change="changeclassEQ"
                  placeholder="请选择设备类型"
                >
                  <el-option
                    v-for="item in typeData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- 1水位监测  2流量监测  4雨量监测 -->
            <div></div>
          </div>
          <div v-if="point_array.length != 0">
            <el-form-item
              :label="item.name"
              v-for="(item, index) in point_array"
              :key="index"
              :required="true"
            >
              <div style="display: flex;">
                <el-input
                  placeholder="请输入测点编号"
                  v-model="item.number"
                  clearable
                >
                </el-input>
                <el-input
                  :change="rule(index, 'min')"
                  placeholder="请输入最小值"
                  v-model="item.min"
                  clearable
                  style="margin-left: 10px;"
                >
                </el-input>
                <el-input
                  style="margin-left: 10px;"
                  :change="rule(index, 'max')"
                  placeholder="请输入最大值"
                  v-model="item.max"
                  clearable
                >
                </el-input>
              </div>
            </el-form-item>
          </div>
<!--          <el-form-item label="nfc编号">
            <el-input
              v-model="liveData.nfc_code"
              placeholder="请输入nfc编号"
            ></el-input>
          </el-form-item>-->
          <el-form-item label="封面图" label-width="130px" :required="true">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :data="uploadData"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :on-exceed="numberExceeded"
              :auto-upload="true"
              accept=".png,.jpg,.jpeg"
              :limit="1"
            >
              <el-button slot="trigger" size="small" type="primary"
                >选取文件
              </el-button>
            </el-upload>
            <div>
              <img
                :src="liveData.cover_id_url"
                alt=""
                v-if="
                  liveData.cover_id_url != '' && liveData.cover_id_url != null
                "
                style="width: 300px; object-fit: cover;margin-top: 5px;"
              />
            </div>
          </el-form-item>
          <div style="display: flex;">
            <div style="width:50%">
              <el-form-item label="设备编号">
                <el-input
                  v-model="liveData.it_code"
                  placeholder="请输入设备编号"
                ></el-input>
              </el-form-item>
            </div>
            <div style="width:50%">
              <el-form-item label="设备型号">
                <el-input
                  v-model="liveData.it_number"
                  placeholder="请输入设备型号"
                ></el-input>
              </el-form-item>
            </div>
          </div>
          <!-- <el-form-item label="河流类型" :required="true">
            <el-select
              v-model="liveData.river_type"
              @change="changeclassType"
              placeholder="请选择河流类型"
            >
              <el-option
                v-for="item in river_typeData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="is_type_name" v-if="is_type" :required="true">
            <el-select
              v-model="liveData.river_id"
              filterable
              @change="changeclassDate"
              :placeholder="is_type_placeholder"
            >
              <el-option
                v-for="item in river_idData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="选择地区">
            <el-cascader
              class="cascader"
              v-model="selelected2"
              :options="area"
              :props="props2"
              clearable
              :popper-class="'hide'"
              ref="areaRef"
              @change="changeArea()"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="选择工程" >
            <el-cascader
              class="cascader"
              v-model="selelected"
              :options="options"
              :props="props"
              clearable
              :popper-class="'hide'"
              ref="cascade"
              @change="changeCity()"
            ></el-cascader>
          </el-form-item>
          <!-- @change="handleChange" -->

          <el-form-item label="安装位置" :required="true">
            <el-button type="primary" @click="openMap"
              >请选择安装位置
            </el-button>
            {{ map_data.poiname }}
          </el-form-item>
          <el-form-item label="投运时间">
            <el-date-picker
              v-model="liveData.use_time"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择投运时间"
              default-time="12:00:00"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="设备责任人">
            <el-input
              v-model="liveData.responsible_2"
              placeholder="请输入设备责任人"
            ></el-input>
          </el-form-item>
          <el-form-item label="责任人联系方式">
            <el-input
              v-model="liveData.responsible_phone_2"
              placeholder="请输入责任人联系方式"
            ></el-input>
          </el-form-item>
          <el-form-item label="生产厂家">
            <el-input
              v-model="liveData.manufacturer"
              placeholder="请输入生产厂家"
            ></el-input>
          </el-form-item>
          <el-form-item label="购买时间">
            <el-date-picker
              v-model="liveData.buy_time"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择购买时间"
              default-time="12:00:00"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="质保期限">
            <el-date-picker
              v-model="liveData.validity_period"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择质保期限"
              default-time="12:00:00"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="经度">
            <el-input
              v-model="liveData.longitude"
              placeholder="请输入经度"
            ></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input
              v-model="liveData.latitude"
              placeholder="请输入纬度"
            ></el-input>
          </el-form-item>
          <el-form-item label="高度">
            <el-input
              v-model="liveData.take_height"
              placeholder="请输入高度"
            ></el-input>
          </el-form-item>
<!--          <el-form-item label="设备二维码" label-width="130px">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :on-preview="handlePreview2"
              :on-remove="handleRemove2"
              :file-list="fileList2"
              :data="uploadData2"
              :before-upload="beforeAvatarUpload2"
              :on-success="handleAvatarSuccess2"
              :on-error="handleAvatarError2"
              :on-exceed="numberExceeded2"
              :auto-upload="true"
              accept=".png,.jpg,.jpeg"
              :limit="1"
            >
              <el-button slot="trigger" size="small" type="primary"
                >选取文件
              </el-button>
            </el-upload>
            <div>
              <img
                :src="liveData.it_qr_url"
                alt=""
                v-if="liveData.it_qr_url != '' && liveData.it_qr_url != null"
                style="width: 300px; object-fit: cover;margin-top: 5px;"
              />
            </div>
          </el-form-item>-->
        </el-form>
      </div>
    </el-card>
    <el-dialog
      title="选择安装位置"
      :visible.sync="dialogVisible"
      :modal-append-to-body="false"
      :destroy-on-close="true"
      center
    >
      <iframe
        id="mapPage"
        width="100%"
        height="520px"
        frameborder="0"
        :src="map_src"
      >
      </iframe>
      <!-- src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=CYQBZ-VGPK4-7JKUQ-XPE3E-SSN3H-EXFVJ&referer=myapp" -->
      <span slot="footer">
        <el-button @click="closeMap">取 消</el-button>
        <el-button type="primary" @click="submitMap">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";

export default {
  name: "liveAdd",
  components: {},
  data() {
    return {
      userInfo: JSON.parse(
        localStorage.getItem(this.$apis.getLocalKey().loginPersonnelInformation)
      ),
      loading: false,

      options: [],
      props: {
        multiple: true,
        expandTrigger: "click"
      },
      area: [],
      props2: {
        multiple: true,
        expandTrigger: "click"
      },
      preValue: [],
      selelected: [],
      selelected2: [],
      deal_select: [],

      //富文本文档类型
      liveData: {
        name: "",
        equipment_type: "",
        nfc_code: "",
        cover_id_url: "",
        it_code: "",
        it_number: "",
        river_type: "",
        river_id: "",
        install_position: "",
        use_time: "",
        responsible_1: "",
        manufacturer: "",
        buy_time: "",
        responsible_2: "",
        responsible_phone_2: "",
        validity_period: "",
        it_qr_url: ""
      },

      typeData: [], //设备类型
      //河流类型
      river_typeData: [
        {
          id: 1,
          name: "河流"
        },
        {
          id: 2,
          name: "水库"
        },
        {
          id: 3,
          name: "坑塘"
        }
      ],
      is_type: false,
      is_type_name: "",
      is_type_placeholder: "",
      river_idData: [], //河流/水库id

      uploadUrl: this.$apis.getUploadUrl() + "/file/upload", //上传地址
      uploadData: {
        type: 1 //没用
      },
      uploadData2: {
        type: 1 //没用
      },
      fileList: [],
      fileList2: [],
      img_id: "",
      img_id2: "",
      addtype: "", //类型add undate

      dialogVisible: false,
      form: {
        //省市区ID
        id_area: [0, 0, 0],
        address: "",
        lng: "",
        lat: ""
      },
      map_src: "",
      map_data: {
        url:
          "https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&key=CYQBZ-VGPK4-7JKUQ-XPE3E-SSN3H-EXFVJ&referer=app name",
        address: "",
        lng: "",
        lat: "",
        poiname: ""
      },

      //设备数组
      point_array: []
    };
  },
  created() {
    var _this = this;
    this.addtype = this.$route.query.type;
    _this.gettypeData(); //设备类型
    _this.getoptionsData(); //选择工程级联列表
    _this.getareaData(); //选择地区级联列表

    // 腾讯地图
    window.addEventListener(
      "message",
      function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module == "locationPicker") {
          console.log("location:", loc);
          _this.map_data.address = loc.poiaddress;
          _this.map_data.lat = loc.latlng.lat;
          _this.map_data.lng = loc.latlng.lng;
          _this.map_data.poiname = loc.poiname;
        }
      },
      false
    );

    if (_this.addtype == "add") {
      _this.initData();
      _this.fileList = [];
      _this.map_src =
        "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=CYQBZ-VGPK4-7JKUQ-XPE3E-SSN3H-EXFVJ&referer=myapp name&coord=35.937224,116.47024";
    }
    if (_this.addtype == "update") {
      _this.liveData = JSON.parse(_this.$route.query.data);
      // console.log("this.liveData:", this.liveData);

      // 地区级联列表回显
      let twoDArray2 = [];
      if (_this.liveData.json_rivers.length > 0) {
        twoDArray2 = _this.liveData.json_rivers.map((item, index) => {
          return ([index] = [item.river_type, item.river_id]);
        });
        _this.selelected2 = twoDArray2;
      }

      // 工程级联列表回显
      let twoDArray = [];
      if (_this.liveData.json_pro.length > 0) {
        twoDArray = _this.liveData.json_pro.map((item, index) => {
          return ([index] = [item.pro_type, item.pro_id]);
        });
        _this.selelected = twoDArray;
      }

      // for (let i = 0; i < _this.liveData.engines.length; i++) {
      //   _this.selelected.push(_this.liveData.engines[i].engine);
      // }
      // _this.preValue = _this.selelected;
      // console.log("_this.selelected:", _this.selelected);

      // _this.preValue = _this.maopao(
      //   JSON.parse(JSON.stringify(_this.selelected))
      // );
      // console.log(
      //   "_this.preValue====",
      //   _this.preValue,
      //   JSON.stringify(_this.preValue)
      // );

      _this.point_array = _this.liveData.point_array;

      // console.log("install_position:", _this.liveData.install_position);
      if (
        _this.liveData.install_position == null ||
        _this.liveData.install_position == ""
      ) {
        this.map_src =
          "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=CYQBZ-VGPK4-7JKUQ-XPE3E-SSN3H-EXFVJ&referer=myapp name&coord=35.937224,116.47024";
      } else {
        // 腾讯地图回显
        var Mapdata = JSON.parse(_this.liveData.install_position);
        // console.log("Mapdata:", Mapdata);
        this.map_data = Mapdata;
        var lat = Mapdata.lat;
        var lng = Mapdata.lng;
        let mat_url = this.map_data.url;
        if (lat && lng) {
          mat_url += "&coord=" + lat + "," + lng;
        }
        this.map_src = mat_url;
        // console.log("this.map_src:", this.map_src);
      }

      // var Mapdata = {
      //   // lat: 36.186875734098734,
      //   // lng: 117.11068825508882,
      //   lat: 36.183015,
      //   lng: 117.123996,

      //   url:
      //     "https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&key=CYQBZ-VGPK4-7JKUQ-XPE3E-SSN3H-EXFVJ&referer=app name"
      // };

      // this.map_data = Mapdata;
      // var lat = Mapdata.lat;
      // var lng = Mapdata.lng;
      // let mat_url = this.map_data.url;
      // if (lat && lng) {
      //   mat_url += "&coord=" + lat + "," + lng;
      // }
      // this.map_src = mat_url;
      // console.log("this.map_src:", this.map_src);

      // this.$jsonp("https://apis.map.qq.com/ws/geocoder/v1/?", {
      //   location: `${Mapdata.lat},${Mapdata.lng}`, // 经纬度
      //   key: "CYQBZ-VGPK4-7JKUQ-XPE3E-SSN3H-EXFVJ", //这里就是要开启那个service不然会报错让你开启
      //   output: "jsonp" // output必须jsonp
      // }).then(res => {
      //   console.log("!!!!!:", res);
      //   //获取到的res 就是继续的地址的所有信息;
      //   this.map_data.poiname = res.result.address;
      // });

      // console.log("this.map_data:", this.map_data);

      if (this.liveData.cover_id != null) {
        var cover_data = {
          name: this.liveData.cover_id_name,
          url: this.liveData.cover_id_url
        };
        this.fileList.push(cover_data);
      }
      if (this.liveData.it_qr != null) {
        var cover_data2 = {
          name: this.liveData.it_qr_name,
          url: this.liveData.it_qr_url
        };
        this.fileList2.push(cover_data2);
      }
      // this.img_id = this.$route.query.data.cover_id;
      this.img_id = JSON.parse(_this.$route.query.data).cover_id;
      // this.img_id2 = this.$route.query.data.it_qr;
      this.img_id2 = JSON.parse(_this.$route.query.data).it_qr;

      if (_this.liveData.river_type == 1) {
        _this.is_type_name = "河流名称";
        _this.is_type_placeholder = "请选择河流";
        _this.$apis.equipment_river_list().then(res => {
          if (res.result == 0) {
            _this.river_idData = res.data;
          }
        });
      } else if (_this.liveData.river_type == 2) {
        _this.is_type_name = "水库名称";
        _this.is_type_placeholder = "请选择水库";
        _this.$apis.equipment_reservoir_list().then(res => {
          if (res.result == 0) {
            _this.river_idData = res.data;
          }
        });
      } else if (_this.liveData.river_type == 3) {
        _this.is_type_name = "坑塘名称";
        _this.is_type_placeholder = "请选择坑塘";
        _this.$apis.equipment_pond_list().then(res => {
          if (res.result == 0) {
            _this.river_idData = res.data;
            _this.is_type = true;
          }
        });
      } else {
        _this.is_type_name = "";
        _this.is_type_placeholder = "";
        console.log("河流/水库类型有误！");
      }
      this.is_type = true;
    }
    console.log("===this.liveData:", _this.liveData);
  },
  beforeDestroy() {
    clearInterval(this.null);
  },
  methods: {
    // //升序（冒泡排序）
    // maopao(arr) {
    //   for (var i = 1; i < arr.length; i++) {
    //     for (var j = 0; j < arr.length - i; j++) {
    //       if (arr[j][0] > arr[j + 1][0]) {
    //         var temp = arr[j]; //定义一个临时变量temp
    //         arr[j] = arr[j + 1];
    //         arr[j + 1] = temp;
    //       }
    //     }
    //   }
    //   return arr; //返回数组
    // },
    // 工程级联选择
    changeCity(items) {
      // console.log(items, this.$refs["cascade"].currentLabels);
      console.log(
        "工程级联选择:",
        this.$refs["cascade"].getCheckedNodes(items)
      );
      let itemArr = [];
      this.$refs["cascade"].getCheckedNodes(items).map(item => {
        itemArr.push({
          pro_type: item.pathNodes[0].value,
          pro_id: item.pathNodes[1].value,
          // pro_id: item.value,
          name: item.pathLabels[0],
          pro_name: item.pathLabels[1]
        });
      });
      // console.log("itemArr:", itemArr);
      // this.itemArr = itemArr;
      this.liveData.json_pro = itemArr;
      console.log("json_pro", this.liveData.json_pro);
    },
    // 地区级联选择
    changeArea(items) {
      console.log("地区级联选择", this.$refs["areaRef"].getCheckedNodes(items));
      let itemArr2 = [];
      this.$refs["areaRef"].getCheckedNodes(items).map(item => {
        itemArr2.push({
          river_type: item.pathNodes[0].value,
          river_id: item.pathNodes[1].value,
          name: item.pathLabels[0],
          river_name: item.pathLabels[1]
        });
      });
      // console.log("itemArr2:", itemArr2);
      // this.itemArr2 = itemArr2;
      this.liveData.json_rivers = itemArr2;
      console.log("json_rivers", this.liveData.json_rivers);
    },

    handleChange(val) {
      // console.log("val:", val, this.preValue);
      let aMap = new Map(); // 父类
      let bv = []; // 要留下的
      val.forEach(valItem => {
        if (!aMap.has(valItem[0])) {
          aMap.set(valItem[0], valItem[1]);
        } else {
          // 重复项
          let old = this.preValue.find(preValueItem =>
            preValueItem.includes(valItem[0])
          );
          // 新 ： 旧
          bv = [
            valItem[0],
            valItem[1] == old[1] ? aMap.get(valItem[0]) : valItem[1]
          ];
        }
      });
      if (bv.length) {
        let narr = val.filter(item => item[0] !== bv[0]); // [[1, 2], [2, 3]]
        narr.push(bv); // [3, 4]
        this.selelected = narr;
        this.preValue = narr;
      } else {
        this.selelected = val;
        this.preValue = val;
      }

      // if (this.preValue.length > 0 && val.length > this.preValue.length) {
      //   console.log("jin");
      //   let newIndex;
      //   let i = 0,
      //     j = 0;
      //   while (i < val.length && j < this.preValue.length) {
      //     if (
      //       val[i][0] === this.preValue[j][0] &&
      //       val[i][1] === this.preValue[j][1]
      //     ) {
      //       i++;
      //       j++;
      //     } else {
      //       //添加在中间的情况
      //       newIndex = i;
      //       break;
      //     }
      //   }
      //   //添加在末尾的情况
      //   if (j === this.preValue.length) {
      //     newIndex = i;
      //   }
      //   // 对比在此之前是否添加过于新增项同一父级下的其他子级
      //   // 存在的话触发取消勾选
      //   let delIndex = val.findIndex(
      //     (item, index) => index !== newIndex && item[0] === val[newIndex][0]
      //   );
      //   if (delIndex >= 0) {
      //     // 取消选择的节点
      //     let cancelIndex;
      //     for (let i = 0; i < this.options.length; i++) {
      //       if (this.options[i].value === val[delIndex][0]) {
      //         for (let j = 0; j < this.options[i].children.length; j++) {
      //           if (this.options[i].children[j].value === val[delIndex][1]) {
      //             cancelIndex = j;
      //             break;
      //           }
      //         }
      //         break;
      //       }
      //     }
      //     // 获取id值
      //     this.$nextTick(() => {
      //       let panelId = this.$refs.cascade.panel.$refs.menu[1].$el.id; //其中menu[1]表示右侧的面板 menu[0]即为左侧的面板
      //       let liId = document.getElementById(panelId + "-" + cancelIndex);
      //       liId.children[0].click();
      //     });
      //     val[delIndex] = "";
      //     val = val.filter(item => item !== "");
      //   }
      // }
      // // preValuee数组来存储上一次的值
      // this.preValue = val;

      // console.log("preValue:", this.preValue);
      // console.log("selelected:", this.selelected);

      /* let deal_data = [];//最终处理好的数据
				 let deal_data_same = [];//取出选择数据和复选数据相同的值
				 let selelected_other = [];//取出选择数据去除相同数据后的值
				 let deal_select_same = [];//取出复选数据中跟选择数据相同的值

				 deal_data_same = this.selelected.filter(item =>
				   this.deal_select.some(i => JSON.stringify(item) === JSON.stringify(i.engine))
				 )

				 selelected_other = [];
				 selelected_other = this.selelected.filter(v => deal_data_same.findIndex(el => JSON.stringify(el) === JSON.stringify(v)) === -1);

				 deal_select_same = [];
				 this.deal_select.map(ds => {
				   deal_data_same.map(dds => {
				     if (JSON.stringify(ds.engine) === JSON.stringify(dds)) {
				       deal_select_same.push(ds)
				     }
				   })
				 })

				 deal_data = [...deal_select_same];
				 selelected_other.map(so => {
				   let ls_data = {
				     id: -1,
				     engine: so
				   }
				   deal_data.push(ls_data)
				 })

				 console.log('相同数据', deal_data_same)
				 console.log('选择数据去除相同的', selelected_other)
				 console.log('复选数据相同', deal_select_same, this.deal_select)
				 console.log('最终处理数据', deal_data)*/
    },

    //地图选点确定
    submitMap() {
      // console.log("map_data:", this.map_data);
      if (this.map_data.lat === "" || this.map_data.lng === "") {
        this.$message.error("请先选择地址！");
        return;
      }
      this.dialogVisible = false;
    },
    openMap() {
      this.dialogVisible = true;
    },
    closeMap() {
      this.dialogVisible = false;
      // this.map_data = {
      //   url:
      //     "https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&key=CYQBZ-VGPK4-7JKUQ-XPE3E-SSN3H-EXFVJ&referer=app name",
      //   address: "",
      //   lng: "",
      //   lat: "",
      //   poiname: ""
      // };
    },

    initData() {
      this.liveData = {
        name: "",
        equipment_type: "",
        nfc_code: "",
        cover_id_url: "",
        it_code: "",
        it_number: "",
        river_type: "",
        river_id: "",
        install_position: "",
        use_time: "",
        responsible_1: "",
        manufacturer: "",
        buy_time: "",
        responsible_2: "",
        responsible_phone_2: "",
        validity_period: "",
        it_qr_url: ""
      };
    },
    changeclassEQ(val) {
      // console.log(val);
      var _this = this;
      this.point_array = [];
      var datas = {
        type: val
      };
      this.$apis.equipment_type_value(datas).then(res => {
        if (res.result == 0) {
          var dataArr = res.data;
          for (let item of dataArr) {
            item.min = "";
            item.max = "";
            item.number = "";
            item.value = item.id;
          }
          _this.point_array = dataArr;
        }
      });
    },
    changeclassDate(val) {
      // console.log(val);
      // console.log("---:", this.liveData.river_id);
    },
    changeclassType(val) {
      var _this = this;
      // console.log(val);
      _this.liveData.river_id = null;
      _this.river_idData = [];
      if (val == 1) {
        _this.is_type_name = "河流名称";
        _this.is_type_placeholder = "请选择河流";
        _this.$apis.equipment_river_list().then(res => {
          if (res.result == 0) {
            _this.river_idData = res.data;
            _this.is_type = true;
          }
        });
      } else if (val == 2) {
        _this.is_type_name = "水库名称";
        _this.is_type_placeholder = "请选择水库";
        _this.$apis.equipment_reservoir_list().then(res => {
          if (res.result == 0) {
            _this.river_idData = res.data;
            _this.is_type = true;
          }
        });
      } else if (val == 3) {
        _this.is_type_name = "坑塘名称";
        _this.is_type_placeholder = "请选择坑塘";
        _this.$apis.equipment_pond_list().then(res => {
          if (res.result == 0) {
            _this.river_idData = res.data;
            _this.is_type = true;
          }
        });
      } else {
        _this.is_type_name = "";
        _this.is_type_placeholder = "";
        console.log("河流/水库类型有误！");
      }
    },
    // 设备类型
    gettypeData() {
      var _this = this;
      var datas = {
        page: _this.page,
        size: 999
      };
      _this.$apis.equipment_type_list(datas).then(res => {
        if (res.result == 0) {
          _this.typeData = res.data;
        }
      });
    },

    // 选择地区级联列表
    getareaData() {
      var _this = this;
      _this.$apis.unitywebpc_address_list().then(res => {
        if (res.result == 0) {
          _this.area = res.data;
        }
      });
    },
    // 选择工程级联列表
    getoptionsData() {
      var _this = this;
      _this.$apis.unitywebpc_engine_list().then(res => {
        if (res.result == 0) {
          _this.options = res.data;
        }
      });
    },
    //上传文件
    submitUpload() {
      this.$refs.upload.submit();
    },
    //文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      // console.log("handleRemove===========", file, fileList);
      this.img_id = "";
      this.fileList = fileList;
      this.liveData.cover_id_url = "";
      // if (this.addtype == "add") {
      //   this.cover_img1 = "";
      // } else {
      //   this.cover_img1 = this.qudata.cover_files_url;
      // }
    },
    handleRemove2(file, fileList) {
      // console.log("handleRemove===========", file, fileList);
      this.img_id2 = "";
      this.fileList2 = fileList;
      this.liveData.it_qr_url = "";
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    handlePreview2(file) {
      console.log(file);
    },
    //文件上传成功的钩子
    handleAvatarSuccess(res, file, fileList) {
      console.log(res);
      this.img_id = res.data.id;
      this.fileList = fileList;
      this.liveData.cover_id_url = res.data.url;
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    handleAvatarSuccess2(res, file, fileList) {
      this.img_id2 = res.data.id;
      this.fileList2 = fileList;
      this.liveData.it_qr_url = res.data.url;
    },
    //文件上传失败时的钩子
    handleAvatarError(err, file) {
      Message.error("文件上传失败，请稍后再试");
    },
    handleAvatarError2(err, file) {
      Message.error("文件上传失败，请稍后再试");
    },
    //文件超出一个
    numberExceeded() {
      Message.error("只能上传一张图片");
    },
    numberExceeded2() {
      Message.error("只能上传一张图片");
    },
    //上传文件之前的钩子
    beforeAvatarUpload(file) {
      var typeList = ["image/jpeg", "image/png", "image/jpg"];
      // const isJPG = file.type === 'image/jpeg'
      const isJPG = typeList.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG或者PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return isJPG && isLt2M;
    },
    beforeAvatarUpload2(file) {
      var typeList = ["image/jpeg", "image/png", "image/jpg"];
      // const isJPG = file.type === 'image/jpeg'
      const isJPG = typeList.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG或者PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return isJPG && isLt2M;
    },
    save() {
      var _this = this;
      var datas = _this.liveData;
      datas.cover_id = _this.img_id;
      datas.it_qr = _this.img_id2;
      // console.log("(_this.selelected):", _this.selelected);
      // console.log("itemArr:", this.itemArr);
      console.log("datas:", datas);
      console.log("地区：", this.selelected2);
      console.log("工程：", this.selelected);
      // console.log("map_data:", this.map_data);
      // var phoneReg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;

      if (datas.name == "") {
        Message.error("设备名称不能为空");
        return;
      }
      if (datas.equipment_type == "") {
        Message.error("设备类型不能为空");
        return;
      }

      for (let item of _this.point_array) {
        if (
          item.number == "" ||
          item.number == null ||
          item.number == undefined
        ) {
          Message.error(item.name + "测点编号不能为空");
          return;
        }
        if (item.min == "" || item.min == null || item.min == undefined) {
          Message.error(item.name + "最小值不能为空");
          return;
        }
        if (item.max == "" || item.max == null || item.max == undefined) {
          Message.error(item.name + "最大值不能为空");
          return;
        }
        if (Number(item.max) < Number(item.min)) {
          Message.error(item.name + "最大值不能小于最小值");
          return;
        }
      }
      datas.point_array = JSON.stringify(_this.point_array);

      // if (datas.nfc_code == "") {
      //   Message.error("nfc编号不能为空");
      //   return;
      // }
      if (datas.cover_id == "") {
        Message.error("封面图不能为空");
        return;
      }
      // if (datas.it_code == "") {
      //   Message.error("设备编号不能为空");
      //   return;
      // }
      // if (datas.it_number == "") {
      //   Message.error("设备型号不能为空");
      //   return;
      // }
      // if (datas.river_type == "") {
      //   Message.error("河流类型不能为空");
      //   return;
      // }
      // if (datas.river_id == "" || datas.river_id == null) {
      //   Message.error("河流/水库名称不能为空");
      //   return;
      // }

      // 选择地区
      // if (_this.selelected2.length == 0) {
      //   Message.error("选择地区不能为空");
      //   return;
      // }
      datas.json_rivers = JSON.stringify(_this.liveData.json_rivers);
      // 选择工程
      // if (_this.selelected.length == 0) {
      //   Message.error("选择工程不能为空");
      //   return;
      // }
      datas.json_pro = JSON.stringify(_this.liveData.json_pro);

      if (this.map_data.lat === "" || this.map_data.lng === "") {
        this.$message.error("请选择安装位置");
        return;
      }
      datas.install_position = JSON.stringify(_this.map_data);

      // if (datas.use_time == "" || datas.use_time == null) {
      //   Message.error("投运时间不能为空");
      //   return;
      // }
      // if (datas.responsible_1 == "") {
      //   Message.error("设备负责人不能为空");
      //   return;
      // }
      // if (datas.manufacturer == "") {
      //   Message.error("生产厂家不能为空");
      //   return;
      // }
      // if (datas.buy_time == "" || datas.buy_time == null) {
      //   Message.error("购买时间不能为空");
      //   return;
      // }
      // if (datas.responsible_2 == "") {
      //   Message.error("设备责任人不能为空");
      //   return;
      // }
      // if (datas.responsible_phone_2 == "") {
      //   Message.error("责任人联系方式不能为空");
      //   return;
      // }
      // if (!/^1[0-9]{10}$/.test(datas.responsible_phone_2)) {
      //   Message.warning("责任人联系方式格式不正确");
      //   return;
      // }
      // if (datas.validity_period == "" || datas.validity_period == null) {
      //   Message.error("质保期限不能为空");
      //   return;
      // }
      // if (datas.it_qr == "") {
      //   Message.error("设备二维码不能为空");
      //   return;
      // }

      if (this.addtype == "add") {
        console.log("save-datas:", datas);
        _this.$apis.equipment_add(datas).then(res => {
          if (res.result == 0) {
            Message.success("添加成功");
            _this.$router.back();
          }
        });
      } else {
        // datas.id = _this.$route.query.data.id;
        datas.id = JSON.parse(_this.$route.query.data).id;
        console.log("update-datas:", datas);
        _this.$apis.equipment_update(datas).then(res => {
          if (res.result == 0) {
            Message.success("修改成功");
            _this.$router.back();
          }
        });
      }
    },

    back() {
      this.$router.back();
    },

    rule(index, type) {
      var _this = this;
      let checkPlan = "" + _this.point_array[index][type];
      if (_this.point_array[index].name == "气温(℃)") {
        // console.log(checkPlan)
        checkPlan = checkPlan
          .replace(/[^\d.-]/g, "") // 清除“数字”和“.”以外的字符
          .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
          .replace(/^\./g, "") // 保证第一个为数字而不是.
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".");

        if (
          checkPlan.indexOf(".") < 0 &&
          checkPlan !== "" &&
          checkPlan !== "-"
        ) {
          // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          checkPlan = parseFloat(checkPlan) + "";
        } else if (checkPlan.indexOf(".") >= 0) {
          if (checkPlan.indexOf("-") >= 0) {
            var copycheckPlan = checkPlan.substring(1);
            checkPlan =
              "-" + copycheckPlan.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
          } else {
            checkPlan = checkPlan.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
          }
        }

        if (checkPlan >= 1 || checkPlan < 0) {
          checkPlan = checkPlan.replace(/^0*/g, ""); // 清除数字之前的0
        } else if (
          checkPlan == "" ||
          checkPlan == null ||
          checkPlan == undefined
        ) {
          checkPlan = "";
        } else if (checkPlan == "-") {
          checkPlan = "-";
        } else {
          checkPlan = checkPlan.replace(/^0*/g, "0"); // 清除数字之前的0
        }
        _this.point_array[index][type] = checkPlan;

        return;
      }
      checkPlan = checkPlan
        .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(/^\./g, "") // 保证第一个为数字而不是.
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      if (checkPlan.indexOf(".") < 0 && checkPlan !== "") {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        checkPlan = parseFloat(checkPlan) + "";
      } else if (checkPlan.indexOf(".") >= 0) {
        checkPlan = checkPlan.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      }
      if (checkPlan >= 1) {
        checkPlan = checkPlan.replace(/^0*/g, ""); // 清除数字之前的0
      } else if (
        checkPlan == "" ||
        checkPlan == null ||
        checkPlan == undefined
      ) {
        checkPlan = "";
      } else {
        checkPlan = checkPlan.replace(/^0*/g, "0"); // 清除数字之前的0
      }
      _this.point_array[index][type] = checkPlan;
    }
  }
};
</script>

<style lang="scss" scoped>
.weizhi2 .weizhi2 .el-dialog__body {
  height: 500px;
}

// .hide {
//   .el-cascader-menu:first-of-type {
//     .el-cascader-node {
//       .el-checkbox {
//         display: none;
//       }
//     }
//   }
//   .el-tag__close {
//     display: none;
//   }
// }

// .el-cascader-panel > div:first-child .el-checkbox {
//   display: none;
// }
</style>

<style lang="scss" scoped>
/deep/ .el-cascader__tags .el-tag .el-icon-close {
  display: none;
}
</style>
